<template>
  <div class="chat-test">
    <h1>聊天功能测试</h1>
    
    <!-- 连接状态 -->
    <div class="connection-status">
      <el-alert 
        :title="wsConnected ? 'WebSocket已连接' : 'WebSocket未连接'" 
        :type="wsConnected ? 'success' : 'error'"
        show-icon
      />
    </div>

    <!-- 用户信息 -->
    <div class="user-info">
      <h3>当前用户信息</h3>
      <p v-if="currentUser">用户ID: {{ currentUser.id }}, 用户名: {{ currentUser.username }}</p>
      <p v-else>未登录</p>
    </div>

    <!-- 创建会话测试 -->
    <div class="session-test">
      <h3>创建聊天会话测试</h3>
      <el-form inline>
        <el-form-item label="目标用户ID">
          <el-input v-model="targetUserId" placeholder="输入目标用户ID" />
        </el-form-item>
        <el-form-item label="房源ID">
          <el-input v-model="houseId" placeholder="输入房源ID（可选）" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="createSession" :loading="creating">创建会话</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 发送消息测试 -->
    <div class="message-test" v-if="sessionId">
      <h3>发送消息测试</h3>
      <p>会话ID: {{ sessionId }}</p>
      <el-form inline>
        <el-form-item label="消息内容">
          <el-input v-model="messageContent" placeholder="输入消息内容" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sendMessage" :loading="sending">发送消息</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 消息列表 -->
    <div class="messages" v-if="messages.length > 0">
      <h3>消息列表</h3>
      <div class="message-list">
        <div v-for="message in messages" :key="message.id" class="message-item">
          <p><strong>发送者:</strong> {{ message.senderId }}</p>
          <p><strong>内容:</strong> {{ message.content }}</p>
          <p><strong>时间:</strong> {{ message.sendTime }}</p>
        </div>
      </div>
    </div>

    <!-- 会话列表测试 -->
    <div class="sessions-test">
      <h3>获取会话列表测试</h3>
      <el-button @click="fetchSessions" :loading="loadingSessions">获取会话列表</el-button>
      <div v-if="sessions.length > 0" class="sessions-list">
        <div v-for="session in sessions" :key="session.sessionId" class="session-item">
          <p><strong>会话ID:</strong> {{ session.sessionId }}</p>
          <p><strong>用户1:</strong> {{ session.userId1 }}</p>
          <p><strong>用户2:</strong> {{ session.userId2 }}</p>
          <p><strong>最后消息:</strong> {{ session.lastMessage }}</p>
        </div>
      </div>
    </div>

    <!-- 日志 -->
    <div class="logs">
      <h3>操作日志</h3>
      <div class="log-list">
        <div v-for="(log, index) in logs" :key="index" class="log-item">
          {{ log }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { createChatSession, sendChatMessage, getChatSessions } from '@/utils/apiService'
import { getUserInfo } from '@/utils/auth'
import chatWebSocket from '@/utils/websocket'

// 响应式数据
const wsConnected = ref(false)
const currentUser = ref(null)
const targetUserId = ref('')
const houseId = ref('')
const sessionId = ref('')
const messageContent = ref('')
const messages = ref([])
const sessions = ref([])
const logs = ref([])

// 加载状态
const creating = ref(false)
const sending = ref(false)
const loadingSessions = ref(false)

// 添加日志
const addLog = (message) => {
  const timestamp = new Date().toLocaleTimeString()
  logs.value.unshift(`[${timestamp}] ${message}`)
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}

// 创建会话
const createSession = async () => {
  if (!targetUserId.value) {
    ElMessage.error('请输入目标用户ID')
    return
  }

  if (!currentUser.value) {
    ElMessage.error('请先登录')
    return
  }

  creating.value = true
  try {
    const sessionData = {
      userId1: currentUser.value.id, // 使用当前登录用户ID
      userId2: parseInt(targetUserId.value),
      houseId: houseId.value ? parseInt(houseId.value) : null
    }

    addLog(`创建会话请求: ${JSON.stringify(sessionData)}`)

    // 使用测试API
    const response = await fetch('/housingHub/test/chat/create-session', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(sessionData)
    })

    const result = await response.json()
    addLog(`API响应: ${JSON.stringify(result)}`)

    if (result.code === 200 || result.code === '200') {
      sessionId.value = result.data.sessionId
      addLog(`会话创建成功，会话ID: ${sessionId.value}`)
      ElMessage.success('会话创建成功')
    } else {
      addLog(`会话创建失败: ${result.message || '未知错误'}`)
      ElMessage.error('会话创建失败: ' + (result.message || '未知错误'))
    }
  } catch (error) {
    addLog(`会话创建错误: ${error.message}`)
    addLog(`错误详情: ${JSON.stringify(error)}`)
    ElMessage.error('会话创建失败: ' + error.message)
  } finally {
    creating.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  if (!messageContent.value) {
    ElMessage.error('请输入消息内容')
    return
  }

  if (!currentUser.value) {
    ElMessage.error('请先登录')
    return
  }

  sending.value = true
  try {
    const messageData = {
      senderId: currentUser.value.id, // 使用当前登录用户ID
      receiverId: parseInt(targetUserId.value),
      content: messageContent.value,
      type: 1,
      houseId: houseId.value ? parseInt(houseId.value) : null
    }

    addLog(`发送消息请求: ${JSON.stringify(messageData)}`)

    // 使用测试API
    const response = await fetch('/housingHub/test/chat/send-message', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(messageData)
    })

    const result = await response.json()
    addLog(`API响应: ${JSON.stringify(result)}`)

    if (result.code === 200 || result.code === '200') {
      addLog(`消息发送成功，消息ID: ${result.data.messageId}`)
      ElMessage.success('消息发送成功')

      // 添加到本地消息列表
      messages.value.push({
        id: result.data.messageId,
        senderId: result.data.senderId,
        content: result.data.content,
        sendTime: result.data.sendTime
      })
    } else {
      addLog(`消息发送失败: ${result.message || '未知错误'}`)
      ElMessage.error('消息发送失败: ' + (result.message || '未知错误'))
    }

    messageContent.value = ''
  } catch (error) {
    addLog(`发送消息错误: ${error.message}`)
    ElMessage.error('发送消息失败: ' + error.message)
  } finally {
    sending.value = false
  }
}

// 获取会话列表
const fetchSessions = async () => {
  loadingSessions.value = true
  try {
    addLog('获取会话列表请求')
    const response = await getChatSessions()

    console.log('🔍 获取会话列表响应:', response)

    // 响应拦截器返回完整的response对象，实际数据在response.data中
    const responseData = response.data

    if (responseData.code === 200 || responseData.code === '200') {
      sessions.value = responseData.data || []
      addLog(`获取会话列表成功，共${sessions.value.length}个会话`)
      ElMessage.success('获取会话列表成功')
    } else {
      addLog(`获取会话列表失败: ${responseData.message}`)
      ElMessage.error('获取会话列表失败: ' + responseData.message)
    }
  } catch (error) {
    addLog(`获取会话列表错误: ${error.message}`)
    ElMessage.error('获取会话列表失败: ' + error.message)
  } finally {
    loadingSessions.value = false
  }
}

// 初始化WebSocket连接
const initWebSocket = async () => {
  try {
    addLog('尝试连接WebSocket')
    await chatWebSocket.connect()
    wsConnected.value = true
    addLog('WebSocket连接成功')

    // 添加消息处理器
    chatWebSocket.addMessageHandler('chat-test', (message) => {
      addLog(`收到WebSocket消息: ${JSON.stringify(message)}`)
      messages.value.push(message)
    })

    // 添加连接状态处理器
    chatWebSocket.addConnectionHandler((connected) => {
      wsConnected.value = connected
      addLog(`WebSocket连接状态变更: ${connected ? '已连接' : '已断开'}`)
    })

  } catch (error) {
    addLog(`WebSocket连接失败: ${error.message}`)
    wsConnected.value = false
  }
}

// 页面初始化
onMounted(async () => {
  // 获取用户信息
  currentUser.value = getUserInfo()
  if (currentUser.value) {
    addLog(`当前用户: ${currentUser.value.username} (ID: ${currentUser.value.id})`)
  } else {
    addLog('用户未登录')
  }

  // 初始化WebSocket
  await initWebSocket()
})

// 页面销毁时清理
onBeforeUnmount(() => {
  chatWebSocket.removeMessageHandler('chat-test')
  chatWebSocket.disconnect()
})
</script>

<style scoped>
.chat-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.connection-status,
.user-info,
.session-test,
.message-test,
.messages,
.sessions-test,
.logs {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.message-list,
.sessions-list,
.log-list {
  max-height: 300px;
  overflow-y: auto;
}

.message-item,
.session-item,
.log-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.log-item {
  font-family: monospace;
  font-size: 12px;
  color: #666;
}
</style>
